package com.xywl.escort.view.order.submit

import android.app.Activity
import android.content.Intent
import android.graphics.Paint
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.adapter.SubmitOrderAdapter
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.*
import com.xywl.escort.common.Constant
import com.xywl.escort.utils.NetworkUtil
import com.xywl.escort.utils.NumberFormatUtils
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.HorizontalDividerItemDecoration
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_submit_order.*
import kotlinx.android.synthetic.main.layout_edit_remarks_view.view.*
import kotlinx.android.synthetic.main.view_order_footer.view.*
import kotlinx.android.synthetic.main.view_order_header.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import java.math.BigDecimal
import javax.inject.Inject

@Route(path = "/xy/order/submit")
class SubmitOrderActivity : BaseActivity(), SubmitOrderContract.View {
    private val REQUEST_CODE_CHOOSE_ADDRESS = 25
    private val REQUEST_CODE_CHOOSE_COUPON = 26

    private lateinit var mAdapter: SubmitOrderAdapter

    private lateinit var headerView: View
    private lateinit var footerView: View

    @Autowired
    @JvmField
    var list: List<ShoppingCartResp.DataBean>? = null

    private var addressBean: AddrBean? = null
    private var coupon: CouponBean? = null

    @Inject
    lateinit var mPresenter: SubmitOrderContract.Presenter

    private var categoryCount = 0

    private var count = BigDecimal("0")
    private var price = BigDecimal("0")
    private var orderAmountTotal = BigDecimal("0")

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_submit_order)
        ARouter.getInstance().inject(this)

        initView()
        initData()
        addListener()
        EventBus.getDefault().register(this)
    }

    private fun initView() {
        showBackButton()
        setTitleText(R.string.order_confirm_order)

        Timber.tag("SubmitOrderActivity").e("list=$list")
        val manager = LinearLayoutManager(this@SubmitOrderActivity)
        manager.orientation = LinearLayoutManager.VERTICAL
        val paint = Paint()
        paint.strokeWidth = 30f
        paint.color = ContextCompat.getColor(this@SubmitOrderActivity, R.color.line_color)
        paint.isAntiAlias = true
        recycler_order.addItemDecoration(HorizontalDividerItemDecoration.Builder(this@SubmitOrderActivity).paint(paint).build())
        recycler_order.layoutManager = manager

        mAdapter = SubmitOrderAdapter(R.layout.item_submit_order, list)
        headerView = layoutInflater.inflate(R.layout.view_order_header, recycler_order.parent as ViewGroup, false)
        footerView = layoutInflater.inflate(R.layout.view_order_footer, recycler_order.parent as ViewGroup, false)
        mAdapter.addHeaderView(headerView)
        mAdapter.addFooterView(footerView)
        recycler_order.adapter = mAdapter

        categoryCount = list!!.size
        for (bean in list!!) {
            count = count.add(bean.amount)
            price = price.add(bean.price.multiply(bean.amount))
        }

        orderAmountTotal = price
        val totalPrice = NumberFormatUtils.getInstance().format2Decimal(price.toDouble())

        setPrice(price)
        val totalPriceStr = "订单总价" + totalPrice + "元"
        footerView.text_total_price.text = totalPriceStr
    }

    private fun setPrice(price: BigDecimal) {
        val text = "合计:" + NumberFormatUtils.getInstance().format2Decimal(price.toDouble()) + "元"
        val spanString = SpannableString(text)
        //再构造一个改变字体颜色的Span
        val span = ForegroundColorSpan(ContextCompat.getColor(this, R.color.aid_prompt_color))
        //将这个Span应用于指定范围的字体
        spanString.setSpan(span, text.lastIndexOf(":") + 1, text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

        text_total.text = spanString

        val strPrice = "实付" + NumberFormatUtils.getInstance().format2Decimal(price.toDouble()) + "元"
        footerView.text_payment.text = strPrice
    }

    private fun initData() {
        mPresenter.takeView(this)
        mPresenter.loadAddrDefault()
    }

    private fun addListener() {
        headerView.text_receipt_info.setOnClickListener {
            ARouter.getInstance().build("/xy/address/manage").withInt("type", 1).navigation(this, REQUEST_CODE_CHOOSE_ADDRESS)
        }

        footerView.layout_red_envelope.setOnClickListener {
            val condMinPrice = price.toDouble()
            ARouter.getInstance()
                    .build("/xy/coupon")
                    .withDouble("condMinPrice", condMinPrice)
                    .withString("useScene", "2")
                    .withInt("type", 1)
                    .navigation(this, REQUEST_CODE_CHOOSE_COUPON)
        }

        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.text_note -> {
                    remark(position)
                }
                else -> {
                }
            }
        }

        text_submit_order.setOnClickListener {
            submitOrder()
        }
    }

    private fun submitOrder() {
        if (!NetworkUtil.isAvailable(this)) {
            ToastUtil.showTip(this, R.string.network_error)
            return
        }
        val req = SubmitOrderReq()
        req.productAmountTotal = price
        req.productCount = count
        req.orderAmountTotal = orderAmountTotal
        req.categoryCount = categoryCount
        if (null != coupon) {
            req.redPacketId = coupon!!.id
            req.regPacketMoney = coupon!!.amountOfMoneyYuan
        }
        val orderItems = ArrayList<SubmitOrderReq.OrderItemBean>()
        for (bean in list!!) {
            val orderItemBean = SubmitOrderReq.OrderItemBean()
            orderItemBean.spuId = bean.spuId
            orderItemBean.spuName = bean.spuName
            orderItemBean.skuId = bean.skuId
            orderItemBean.skuName = bean.skuName
            orderItemBean.price = bean.price
            orderItemBean.originalPrice = bean.originalPrice
            orderItemBean.imageUrl = bean.imageUrl
            orderItemBean.amount = bean.amount
            val subTotal = bean.price.multiply(bean.amount)
            orderItemBean.subTotal = subTotal
            orderItemBean.remark = bean.note
            orderItems.add(orderItemBean)
        }
        req.orderItems = orderItems
        if (null != addressBean) {
            if (null != addressBean!!.id && null != addressBean!!.contactNumber && null != addressBean!!.city
                    && null != addressBean!!.district && null != addressBean!!.address && null != addressBean!!.contacts
                    && null != addressBean!!.province) {
                req.addressId = addressBean!!.id
            } else {
                ToastUtil.showTip(this@SubmitOrderActivity, "请选择地址")
                return
            }
        } else {
            ToastUtil.showTip(this@SubmitOrderActivity, "请选择地址")
            return
        }
        mPresenter.submitOrder(req)
    }

    private fun remark(position: Int) {
        val bean = list!![position]
        val edView = LayoutInflater.from(this).inflate(R.layout.layout_edit_remarks_view, null)
        val editText = edView.edit_remark
        val builder = AlertDialog.Builder(this)
        builder.setTitle("输入备注")
        builder.setView(edView)
        builder.setNegativeButton(R.string.confirm) { _, _ ->
            val remarkStr = editText.text.toString()
            bean.note = remarkStr
            mAdapter.notifyDataSetChanged()
        }
        val dialog = builder.create()
        dialog.show()
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }


    override fun loadAddrSuccess(resp: DefaultResp?) {
        addressBean = resp!!.data
        setAddressInfo(addressBean)
    }

    private fun setAddressInfo(bean: AddrBean?) {
        if (null != bean) {
            headerView.text_name.text = bean.contacts
            val contactNumber = bean.contactNumber
            headerView.text_phone.text = contactNumber
            val province = bean.province
            val city = bean.city
            val district = bean.district
            val address = bean.address
            if (TextUtils.isEmpty(province) || TextUtils.isEmpty(city) || TextUtils.isEmpty(address)) {
                headerView.text_empty_address.visibility = View.VISIBLE
                headerView.layout_address.visibility = View.GONE
            } else {
                headerView.text_empty_address.visibility = View.GONE
                headerView.layout_address.visibility = View.VISIBLE
                val detailAddress = province + city + district + address
                headerView.text_address.text = detailAddress
            }
        }
    }

    override fun loadAddrFailure() {
        Timber.tag("SubmitOrderActivity").e("loadAddrFailure")
    }

    override fun submitOrderSuccess(dataBean: SubmitOrderResp.DataBean?) {
        Timber.tag("SubmitOrderActivity").e("dataBean$dataBean")

        val orderId = dataBean!!.id
        val payMoney = orderAmountTotal
        ARouter.getInstance()
                .build("/xy/product/pay/dialog")
                .withString("orderId", orderId)
                .withObject("payMoney", payMoney)
                .withInt("type", 2)
                .navigation()
    }

    override fun submitOrderFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
        Timber.tag("SubmitOrderActivity").e("msg=$msg")
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun mainEventBus(event: MessageEvent) {
        Timber.tag("SubmitOrderActivity").e("event.message=" + event.message)
        Timber.tag("SubmitOrderActivity").e("event.type=" + event.type)
        when (event.type) {
            Constant.EventType.EVENT_PAY_SUCCESS -> {
                val message = event.message
                if (!TextUtils.isEmpty(message)) {
                    if (message == Constant.EventMessage.PAY_SUCCESS || message == Constant.EventMessage.PAY_BALANCE_SUCCESS
                            || message == Constant.EventMessage.PAY_BALANCE_CANCEL) {
                        finish()
                    }
                }
            }
            else -> {
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_CHOOSE_ADDRESS -> {
                    data?.let {
                        addressBean = data.getSerializableExtra("address") as AddrBean
                        Timber.tag("SubmitOrderActivity").e("bean=${addressBean!!.address}")
                        setAddressInfo(addressBean)
                    }
                    Timber.tag("SubmitOrderActivity").e("data=$data")
                }
                REQUEST_CODE_CHOOSE_COUPON -> {
                    data?.let {
                        coupon = data.getSerializableExtra("coupon") as CouponBean
                        Timber.tag("SubmitOrderActivity").e("coupon.name=${coupon!!.name}")
                        val money = "" + coupon!!.amountOfMoneyYuan + "元"
                        footerView.text_red_envelope_info.text = money
                        orderAmountTotal = price.subtract(coupon!!.amountOfMoneyYuan)

                        if (orderAmountTotal.toDouble() < 0) {
                            orderAmountTotal = BigDecimal("0")
                        }

                        setPrice(orderAmountTotal)
                    }
                    Timber.tag("SubmitOrderActivity").e("data=$data")
                }
                else -> {
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}
